<template>
  <div class="rule-container">
    <px-scrollbar class="rule-content">
      <px-button class="mt-[16px]" icon="ArrowLeft" type="primary" @click="handleCancel">返回 </px-button>
      <px-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <px-row class="w-full">
              <px-col :span="8">
                <px-form-item label="科室" prop="className">
                  <px-select v-model="form.className" placeholder="请选择科室" filterable :disabled="isDisabled" @change="classChanged">
                    <px-option v-for="item in classNameList" :key="item.code" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="系统" prop="systemCode">
                  <px-tree-select
                    v-model="form.systemCode"
                    clearable
                    filterable
                    :props="defaultProps"
                    :data="filterSystemList"
                    :disabled="isDisabled"
                    check-strictly
                    node-key="code"
                    placeholder="请选择设备系统（树状图）"
                    @node-click="handleNodeClick"
                    @change="systemCodeChanged"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="form.eqpId"
                    disabled
                    placeholder="请点击选择"
                    maxlength="50"
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" :disabled="isDisabled" @click="dialogVisible = true">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="form.eqpName" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备位置" prop="eqpPosition">
                  <px-input v-model="form.eqpPosition" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="规则类型" prop="ruleTypeCode">
                  <px-select v-model="form.ruleTypeCode" placeholder="请选择规则类型" clearable filterable :disabled="isDisabled">
                    <px-option v-for="item in ruleTypeList" :key="item.code" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown v-for="item in STATUS_LIST" :key="item.code" :dropdownTitle="`【${item.name}】 状态`">
          <template v-slot:content>
            <px-row class="w-full">
              <px-col :span="12">
                <px-form-item label="状态启用" :prop="`${item.code}.isEnabled`">
                  <px-switch v-model="form[item.code].isEnabled" :disabled="isDisabled" />
                </px-form-item>
              </px-col>
              <template v-if="form[item.code].isEnabled">
                <px-col :span="24">
                  <px-form-item label="点位列表" :prop="`${item.code}.eqpRunStatusPointList`">
                    <px-button type="primary" :disabled="isDisabled" @click="handleSelectPoint(item.code)">选择点位</px-button>
                    <px-table class="mt-[16px]" :data="form[item.code].eqpRunStatusPointList" size="small" border max-height="240">
                      <px-table-column prop="tagCode" label="点位编码" show-overflow-tooltip />
                      <px-table-column prop="tagComment" label="点位描述" show-overflow-tooltip />
                      <px-table-column prop="tagUnitDesc" label="点位单位" show-overflow-tooltip />
                      <px-table-column prop="dataType" label="数据类型" show-overflow-tooltip />
                      <px-table-column prop="eqpId" label="设备编码" show-overflow-tooltip />
                      <px-table-column prop="classNameDesc" label="科室" show-overflow-tooltip />
                      <px-table-column fixed="right" label="操作" width="200" align="center">
                        <template #default="scope">
                          <px-tooltip content="移除" placement="top">
                            <px-button link type="primary" icon="Delete" :disabled="isDisabled" @click="handleDelete(item.code, scope.row)" />
                          </px-tooltip>
                        </template>
                      </px-table-column>
                    </px-table>
                  </px-form-item>
                </px-col>
                <px-col :span="24">
                  <px-form-item label="规则" :prop="`${item.code}.formula`">
                    <px-input v-model="form[item.code].formula" type="textarea" :disabled="isDisabled" />
                  </px-form-item>
                </px-col>
              </template>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <template v-if="props.type === 'detail'">
        <px-button type="primary" @click="handleCancel">关 闭</px-button>
      </template>
      <template v-else>
        <px-button @click="handleCancel">取 消</px-button>
        <px-button type="primary" @click="handleSubmit">保 存</px-button>
      </template>
    </div>
    <!-- 选择设备弹窗 -->
    <EquipIdSelectDialog
      :visible="dialogVisible"
      :className="form.className"
      :systemCodes="selectedSystemCodeList"
      @closeEquipDialog="closeEquipDialog"
      @changeEqpId="changeEqpId"
    />
    <PointSelect v-if="showSelect" :eqpId="form.eqpId" @select="selectCallback" @close="closeDialog" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { PxMessageBox, PxMessage } from "px-ui";

import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";

import type { PartialRuleSetting } from "@/api/system/runningStatusSetting/ruleSetting";
import { addRuleForSetting, updateRuleForSetting, getRuleInfoForSetting } from "@/api/system/runningStatusSetting/ruleSetting";

import PointSelect from "./PointSelect.vue";
import { STATUS_LIST, STATUS_LIST_CODE } from "../../constant";
import { IEmitsTypeForSettingEdit, PropsTypeForSettingEdit } from "../../type";
import { useBaseInfo, usePointsSelect, useValidate } from "../../hooks";

const props = defineProps<PropsTypeForSettingEdit>();
const emits = defineEmits<IEmitsTypeForSettingEdit>();

const form = ref({
  className: "",
  systemCode: "",
  eqpId: "",
  eqpName: "",
  eqpPosition: "",
  ruleTypeCode: "",
  runRule: {
    isEnabled: false,
    eqpRunStatusPointList: [],
    formula: ""
  },
  faultRule: {
    isEnabled: false,
    eqpRunStatusPointList: [],
    formula: ""
  },
  diseaseRule: {
    isEnabled: false,
    eqpRunStatusPointList: [],
    formula: ""
  },
  offlineRule: {
    isEnabled: false,
    eqpRunStatusPointList: [],
    formula: ""
  },
  awaitRule: {
    isEnabled: false,
    eqpRunStatusPointList: [],
    formula: ""
  }
});
const formRef = ref(null);

const isDisabled = computed(() => {
  if (props.type === "detail") return true;
  return false;
});

const params = computed<PartialRuleSetting>(() => {
  const obj: PartialRuleSetting = {
    eqpId: form.value.eqpId,
    ruleTypeCode: form.value.ruleTypeCode
  };
  if (props.type === "edit") {
    obj.id = props.ruleId;
  }
  STATUS_LIST.forEach(item => {
    if (form.value[item.code].isEnabled) {
      obj[item.code] = {
        ...form.value[item.code],
        eqpRunStatusPointList: form.value[item.code].eqpRunStatusPointList.map(point => point.tagCode)
      };
    }
  });
  return obj;
});

const {
  defaultProps,
  ruleTypeList,
  classNameList,
  dialogVisible,
  selectedSystemCodeList,
  filterSystemList,
  handleNodeClick,
  closeEquipDialog,
  changeEqpId,
  classChanged,
  systemCodeChanged
} = useBaseInfo(form);

const { rules } = useValidate(form);

const { showSelect, handleDelete, handleSelectPoint, selectCallback, closeDialog } = usePointsSelect(form);

const handleClose = () => {
  formRef.value?.resetFields();
  emits("close");
};

const handleCancel = () => {
  if (props.type === "detail") {
    emits("close");
    return;
  }
  PxMessageBox.confirm(`取消后您填写的内容将会丢失，请确认是否取消?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      handleClose();
    })
    .catch(() => {});
};
const handleSubmit = async () => {
  try {
    const isValid = await formRef.value?.validate();
    if (isValid) {
      if (props.type === "add") {
        await addRuleForSetting(params.value);
        PxMessage.success("添加成功");
      } else if (props.type === "edit") {
        await updateRuleForSetting(params.value);
        PxMessage.success("更新成功");
      }
      handleClose();
    }
  } catch (error) {
    console.log(error);
  }
};

const getRuleInfo = async () => {
  const res = await getRuleInfoForSetting(props.ruleId);
  Object.keys(form.value).forEach(key => {
    if (STATUS_LIST_CODE.includes(key)) {
      if (res[key]) {
        form.value[key] = {
          ...res[key],
          isEnabled: true
        };
      }
    } else {
      form.value[key] = res[key];
    }
    if (key === "eqpPosition") {
      form.value[key] = (res as any).positionNameAll;
    }
  });
};

if (props.type !== "add") {
  getRuleInfo();
}
</script>

<style lang="scss" scoped>
@import url("../../scss/add-detail.scss");
</style>
